/*封装axios*/

//1.引入axios,VueAxios
import axios from 'axios';
//import vueAxios from "vue-axios";

//全局配置
// axios.defaults.baseURL = 'http://mall-pre.springboot.cn';
axios.defaults.timeout = 5000;

//错误拦截
axios.interceptors.response.use(function (response) {
    //console.log(response);
    let res = response.data;
    let path = location.hash;
    if (res.status == 0) {//0是成功
        //console.log(res);
        return res;
    } else if (res.status == 10) {//10是未登录
        if (path != '#/index') {
            window.location.href = '/#/login';
        }
    } else {
        alert(res.msg);
        return Promise.reject(res)
    }
});

//封装get/post方法
/*export default {
    get: function (path = '', data = {}) {
        return new Promise(function (resolve, reject) {
            axios.get(path, {
                params: data
            }).then(function (response) {
                // 按需求来，这里我需要的是response.data，所以返回response.data，一般直接返回response
                resolve(response);
            }).catch(function (error) {
                reject(error);
            });
        });
    },
    post: function (path = '', data = {}) {
        return new Promise(function (resolve, reject) {
            axios.post(path, data).then(function (response) {
                resolve(response);
            }).catch(function (error) {
                reject(error);
            });
        });
    }
};*/

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}


